package com.hkjtgc.pcr_app.view;


import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hkjtgc.pcr_app.R;


/**
 * 搜索文本框
 *
 * <ul>
 * <li>使用 {@link #setHintText(String)} 设置没有文字时的提示</li>
 * <li>使用 {@link #setAutoSearch(boolean)} 设置为自动搜索</li>
 * <li>使用 {@link #setOnTextClearListener(ClearableEditText.OnTextClearListener)} 设置文本清空时的监听器</li>
 * <li>使用 {@link #setOnSearchListener(OnSearchListener)} 通过监听器设置搜索方法，在自动搜索模式下才会工作</li>
 * <li>使用 {@link #search()} 主动搜索</li>
 * <li>使用 {@link #showClear()} 显示清除按钮</li>
 * <li>使用 {@link #dismissClear()} 隐藏清除按钮</li>
 * </ul>
 * <p>在 xml 直接引用即可</p>
 */
public class SearchEditText extends LinearLayout implements TextWatcher {
    private boolean autoSearch;
    private EditText edit;
    private Context context;
    private RelativeLayout clear;
    private ImageView icon;
    private TextView tvName;
    private LinearLayout llLayout;

    public interface OnSearchListener {
        void onSearch(SearchEditText sender, String searchText);
    }

    public SearchEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView(context);
    }


    public SearchEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public SearchEditText(Context context) {
        super(context);
        initView(context);
    }

    protected int getLayout() {
        return R.layout.view_search_edit;
    }

    protected void initView(final Context context) {
        this.context = context;
        LayoutInflater.from(context).inflate(getLayout(), this);
        edit = (EditText) findViewById(R.id.edit);
        tvName = findViewById(R.id.tv_name);
        llLayout = findViewById(R.id.ll_layout);
        llLayout.setBackgroundResource(R.drawable.bg_search_frame);
        clear = (RelativeLayout) findViewById(R.id.clear);
        clear.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                edit.setText("");
                edit.requestFocus();
                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(edit, 0);
            }
        });
        icon = (ImageView) findViewById(R.id.icon);
        edit.addTextChangedListener(this);
        edit.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    if (onSearchListener != null) {
                        closeKey();
                        onSearchListener.onSearch(SearchEditText.this, edit.getText().toString().trim());
                    }
                }
                return false;
            }

        });
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (autoSearch && s.toString().length() >= 0) {
            // 文本改变时自动搜索
            if (onSearchListener != null) {
                onSearchListener.onSearch(this, edit.getText().toString().trim());
            }
            if (onTextClearListener != null && s.toString().length() == 0) {
                onTextClearListener.onClear(new ClearableEditText(context));
            }
        }
        if (textChangeListener != null) {
            textChangeListener.onChange(s.toString());
        }
    }

    public void setOnEditorActionListener(TextView.OnEditorActionListener onEditorActionListener) {
        edit.setOnEditorActionListener(onEditorActionListener);
    }

    public LinearLayout getLlLayout() {
        return llLayout;
    }

    public EditText getView() {
        return edit;
    }

    public View getImageView() {
        return icon;
    }

    public TextView getTvName() {
        return tvName;
    }

//    @Override
//    protected void onFinishInflate() {
//        super.onFinishInflate();
////		setDrawableLeft(R.drawable.icn_search);
//        setImeOptions(EditorInfo.IME_ACTION_SEARCH);
//    }

    public void setText(String str) {
        edit.setText(str);
    }

    public Editable getText() {
        return edit.getText();
    }

    public void setHintText(String hintText) {
        edit.setHint(hintText);
    }
//

    /**
     * 主动调用搜索监听器
     */
    public void search() {
        if (onSearchListener != null) {
            closeKey();
            onSearchListener.onSearch(this, edit.getText().toString());
        }
    }

    public void showClear() {
        clear.setVisibility(VISIBLE);
    }

    public void dismissClear() {
        clear.setVisibility(GONE);
    }

    /**
     * 是否在文本改变后自动搜索
     *
     * @return
     */
    public boolean isAutoSearch() {
        return autoSearch;
    }

    /**
     * 设置是否自动搜索
     *
     * @param autoSearch
     */
    public void setAutoSearch(boolean autoSearch) {
        this.autoSearch = autoSearch;
    }

    public void closeKey() {
        InputMethodManager imm = (InputMethodManager) getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public void openKey() {
        edit.requestFocus();
        InputMethodManager imm = (InputMethodManager) getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    }

    private OnSearchListener onSearchListener;

    /**
     * 设置用来搜索的监听器
     */
    public void setOnSearchListener(OnSearchListener onSearchListener) {
        this.onSearchListener = onSearchListener;
    }

    ClearableEditText.OnTextClearListener onTextClearListener = null;

    public void setOnTextClearListener(ClearableEditText.OnTextClearListener onTextClearListener) {
        this.onTextClearListener = onTextClearListener;
    }

    TextChangeListener textChangeListener;

    public void setTextChangeListener(TextChangeListener textChangeListener) {
        this.textChangeListener = textChangeListener;
    }

    public interface TextChangeListener {
        void onChange(String txt);
    }
}

